//Forzando Commit
package es.ceura.tfg.login;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import es.ceura.tfg.connection.ConnectorMySQL;





/**
 * Servlet implementation class LoginCheck
 */
@WebServlet("/LoginCheck")
public class LoginCheck extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginCheck() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init(){
    	
    	
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession sesion = request.getSession();
		Enumeration<String> parameterNames = request.getParameterNames();
		while(parameterNames.hasMoreElements())
			System.out.println(parameterNames.nextElement());
			
		System.out.println(request.getParameter("nombreUsuario"));
		String usuario = request.getParameter("nombreUsuario");	
		
		String path = this.getInitParameter("HTML_PATH");
		String redireccion = null;
		
		try {
			// Iniciamos la conexion
			Connection conn = ConnectorMySQL.connect();
			
			String sqlConsulta = "select * from users where nombre=##nombre##;";
			sqlConsulta = sqlConsulta.replaceAll("##nombre##", usuario);
						
			Statement consulta = conn.createStatement();
						
			ResultSet result = consulta.executeQuery(sqlConsulta);
			String nombre = null;
			if (result.next())
				nombre = result.getString("nombre");
			if (nombre.equals(usuario)){
				if (sesion != null){
					sesion.setAttribute("nombreAutorizado", nombre);
					redireccion="test.jsp";
				}else{
					redireccion="error/error_plataforma.html";
				}
			}else {
				redireccion ="error/error.jsp";
			}	
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		RequestDispatcher dispatcher = request.getRequestDispatcher(path+redireccion);
		dispatcher.forward(request, response);
		
	}

}
